import { useForm } from "@tanstack/react-form";

import type { Template, TemplateSection, TemplateStorage } from "@hypr/store";
import { Input } from "@hypr/ui/components/ui/input";
import { Textarea } from "@hypr/ui/components/ui/textarea";

import * as main from "../../../../store/tinybase/main";
import { DangerZone } from "../resource-list";
import { RelatedSessions } from "./related-sessions";
import { SectionsList } from "./sections-editor";

function normalizeTemplatePayload(template: unknown): Template {
  const record = (
    template && typeof template === "object" ? template : {}
  ) as Record<string, unknown>;

  let sections: TemplateSection[] = [];
  if (typeof record.sections === "string") {
    try {
      sections = JSON.parse(record.sections);
    } catch {
      sections = [];
    }
  } else if (Array.isArray(record.sections)) {
    sections = record.sections.map((s: unknown) => {
      const sec = s as Record<string, unknown>;
      return {
        title: typeof sec.title === "string" ? sec.title : "",
        description: typeof sec.description === "string" ? sec.description : "",
      };
    });
  }

  let targets: string[] = [];
  if (typeof record.targets === "string") {
    try {
      targets = JSON.parse(record.targets);
    } catch {
      targets = [];
    }
  } else if (Array.isArray(record.targets)) {
    targets = record.targets.filter((t): t is string => typeof t === "string");
  }

  return {
    user_id: typeof record.user_id === "string" ? record.user_id : "",
    created_at: typeof record.created_at === "string" ? record.created_at : "",
    title: typeof record.title === "string" ? record.title : "",
    description:
      typeof record.description === "string" ? record.description : "",
    sections,
    targets,
  };
}

export function TemplateForm({
  id,
  handleDeleteTemplate,
}: {
  id: string;
  handleDeleteTemplate: (id: string) => void;
}) {
  const row = main.UI.useRow("templates", id, main.STORE_ID);
  const value = row ? normalizeTemplatePayload(row) : undefined;

  const handleUpdate = main.UI.useSetPartialRowCallback(
    "templates",
    id,
    (row: Partial<Template>) =>
      ({
        ...row,
        sections: row.sections ? JSON.stringify(row.sections) : undefined,
        targets: row.targets ? JSON.stringify(row.targets) : undefined,
      }) satisfies Partial<TemplateStorage>,
    [id],
    main.STORE_ID,
  );

  const form = useForm({
    defaultValues: {
      title: value?.title ?? "",
      description: value?.description ?? "",
      sections: value?.sections ?? [],
    },
    listeners: {
      onChange: ({ formApi }) => {
        queueMicrotask(() => {
          const {
            form: { errors },
          } = formApi.getAllErrors();
          if (errors.length === 0) {
            formApi.handleSubmit();
          }
        });
      },
    },
    onSubmit: ({ value }) => {
      handleUpdate(value);
    },
  });

  if (!value) {
    return (
      <div className="h-full flex items-center justify-center">
        <p className="text-sm text-neutral-500">Template not found</p>
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col h-full">
      <div className="px-6 py-4 border-b border-neutral-200">
        <form.Field name="title">
          {(field) => (
            <Input
              value={field.state.value}
              onChange={(e) => field.handleChange(e.target.value)}
              placeholder="Enter template title"
              className="border-0 shadow-none text-lg font-semibold px-0 focus-visible:ring-0 h-8"
            />
          )}
        </form.Field>
        <form.Field name="description">
          {(field) => (
            <Textarea
              value={field.state.value}
              onChange={(e) => field.handleChange(e.target.value)}
              placeholder="Describe the template purpose..."
              className="border-0 shadow-none px-0 text-sm text-neutral-600 resize-none focus-visible:ring-0 min-h-[40px]"
              rows={2}
            />
          )}
        </form.Field>
        {value.targets && value.targets.length > 0 && (
          <div className="flex items-center gap-2 flex-wrap mt-2">
            {value.targets.map((target, index) => (
              <span
                key={index}
                className="text-xs text-neutral-600 bg-neutral-100 px-2 py-0.5 rounded"
              >
                {target}
              </span>
            ))}
          </div>
        )}
      </div>

      <div className="flex-1 overflow-y-auto">
        <div className="p-6 border-b border-neutral-200">
          <h3 className="text-sm font-medium text-neutral-600 mb-3">
            Sections
          </h3>
          <form.Field name="sections">
            {(field) => (
              <SectionsList
                disabled={false}
                items={field.state.value}
                onChange={(items) => field.handleChange(items)}
              />
            )}
          </form.Field>
        </div>

        <div className="p-6 border-b border-neutral-200">
          <h3 className="text-sm font-medium text-neutral-600 mb-4">
            Related Notes
          </h3>
          <RelatedSessions templateId={id} />
        </div>

        <div className="p-6">
          <DangerZone
            title="Delete this template"
            description="This action cannot be undone"
            buttonLabel="Delete Template"
            onAction={() => handleDeleteTemplate(id)}
          />
        </div>

        <div className="pb-96" />
      </div>
    </div>
  );
}
